<template>
  <div class="mcq-container">
    <el-card class="box-card" v-if="!isLoading && question">
      <template #header>
        <div class="card-header">
          <span>{{ question.category }}</span>
          <el-tag :type="difficultyTag(question.difficulty)" effect="dark" round>{{ question.difficulty }}</el-tag>
        </div>
      </template>

      <div class="question-content">
        <p class="question-text">{{ question.question }}</p>

        <el-radio-group v-model="selectedAnswer" class="options-group" :disabled="isAnswered">
          <el-radio
              v-for="option in question.options"
              :key="option"
              :label="option"
              size="large"
              border
              class="option-item"
              :class="{
              correct: isAnswered && option === correctAnswer,
              incorrect: isAnswered && option === selectedAnswer && option !== correctAnswer
            }"
          >
            {{ option }}
          </el-radio>
        </el-radio-group>
      </div>

      <div class="card-footer">
        <el-button
            v-if="!isAnswered"
            type="primary"
            @click="submitAnswer"
            :disabled="!selectedAnswer"
            :loading="isSubmitting"
            round
            size="large"
        >
          提交答案
        </el-button>
        <el-button
            v-else
            type="success"
            @click="fetchQuestion"
            round
            size="large"
        >
          下一题 <el-icon class="el-icon--right"><ArrowRightBold /></el-icon>
        </el-button>
      </div>
    </el-card>

    <!-- Loading State -->
    <div v-if="isLoading" class="status-placeholder">
      <el-icon class="is-loading" :size="40"><Loading /></el-icon>
      <p>正在获取题目...</p>
    </div>

    <!-- Error State -->
    <div v-if="error" class="status-placeholder">
      <el-icon :size="40" color="#F56C6C"><CircleCloseFilled /></el-icon>
      <p>{{ error }}</p>
      <el-button type="primary" @click="fetchQuestion" round>重试</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElIcon, ElRadioGroup, ElRadio, ElCard, ElTag, ElButton } from 'element-plus';
import { Loading, CircleCloseFilled, ArrowRightBold } from '@element-plus/icons-vue';
import quizService from '@/services/quizService';
import creditService from '@/services/creditService';
import { methods } from '@/utils/methods';
import { userManager } from '@/utils/user';

const isLoading = ref(true);
const isSubmitting = ref(false);
const error = ref(null);
const question = ref(null);
const selectedAnswer = ref('');
const isAnswered = ref(false);
const correctAnswer = ref('');

const difficultyTag = (difficulty) => {
  if (difficulty === 'hard') return 'danger';
  if (difficulty === 'medium') return 'warning';
  return 'success'; // easy
};

const fetchQuestion = async () => {
  isLoading.value = true;
  error.value = null;
  question.value = null;
  isAnswered.value = false;
  selectedAnswer.value = '';
  correctAnswer.value = '';

  try {
    const response = await quizService.getMcqQuestion();
    if (response.code === 1000 && response.data) {
      question.value = response.data;
    } else {
      throw new Error(response.msg || 'Failed to get question.');
    }
  } catch (e) {
    error.value = e.message || 'Could not connect to the server.';
  } finally {
    isLoading.value = false;
  }
};

const submitAnswer = async () => {
  if (!selectedAnswer.value) {
    ElMessage.warning('Please select an answer.');
    return;
  }
  isSubmitting.value = true;
  try {
    const response = await quizService.submitMcqAnswer(question.value.questionId, selectedAnswer.value);
    isAnswered.value = true;
    if (response.code === 1000) {
      if(response.msg=='恭喜！累计答对5题，获得10学分！')
    {
      creditService.addNewCredit(10,null,methods.SELECTIVE_ANSWERING,userManager.getUserId(),(res)=>{
        
      })

    }
      ElMessage.success(response.msg || 'Correct! You earned a credit.');
      correctAnswer.value = selectedAnswer.value; // Mark the selected one as correct
    } else {
      // Extract correct answer from error message if available
      const msg = response.msg || 'Incorrect answer.';
      const answerPrefix = "The correct answer was: ";
      if (msg.includes(answerPrefix)) {
        correctAnswer.value = msg.substring(msg.indexOf(answerPrefix) + answerPrefix.length);
      }
      ElMessage.error(msg);
    }
  } catch (e) {
    ElMessage.error('An error occurred while submitting.');
  } finally {
    isSubmitting.value = false;
  }
};

onMounted(() => {
  fetchQuestion();
});
</script>

<style scoped>
.mcq-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 60px);
  background-color: #f0f2f5;
  padding: 20px;
}
.box-card {
  width: 100%;
  max-width: 650px;
  border-radius: 15px;
  border: 1px solid #dcdfe6;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}
.question-content {
  padding: 20px 0;
}
.question-text {
  font-size: 1.2em;
  font-weight: 500;
  margin-bottom: 25px;
  line-height: 1.6;
}
.options-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
}
.option-item {
  width: 100%;
  margin-right: 0;
  transition: all 0.2s ease-in-out;
}
.option-item:hover {
  transform: scale(1.02);
}
.option-item.correct {
  --el-radio-button-checked-bg-color: var(--el-color-success);
  --el-radio-button-checked-border-color: var(--el-color-success);
}
.option-item.incorrect {
  --el-radio-button-checked-bg-color: var(--el-color-danger);
  --el-radio-button-checked-border-color: var(--el-color-danger);
}
.card-footer {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}
.status-placeholder {
  text-align: center;
  color: #606266;
}
.status-placeholder p {
  margin-top: 10px;
}
.status-placeholder .el-button {
  margin-top: 20px;
}
</style>

